from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.serializers import jwt_decode_handler
from xyz.models import Reply


class ReplyquestionListAPIView(APIView):
    def post(self, request):
        try:

            token = self.request.auth

            token_user = jwt_decode_handler(token)

            user_id = token_user['user_id']

        except Exception as e:

            return Response(status=404)

        problem = self.request.data.get('problem')
        content = self.request.data.get('content')
        type = self.request.data.get('type')
        parent = self.request.data.get('parent')
        if type == '1':
            data = Reply.objects.create(user_id=user_id, problem_id=problem, content=content, type=type, parent=parent)
        else:
            data = Reply.objects.create(user_id=user_id, problem_id=problem, content=content, type=type)

        return Response({'messgae': '回答问题',
                         'success': True})


class PutReplyuseful(APIView):


    def put(self, request, id):

        try:

            token = self.request.auth

            token_user = jwt_decode_handler(token)

            user_id = token_user['user_id']

        except Exception as e:

            return Response(status=404)

        count = Reply.objects.get(user_id=user_id, id=id)

        count.useful_count += 1

        count.save()

        return Response({'messgae': '回答有用',
                         'success': True})


class PutReplyunuseful(APIView):


    def put(self, request, id):

        try:

            token = self.request.auth

            token_user = jwt_decode_handler(token)

            user_id = token_user['user_id']

        except Exception as e:

            return Response(status=404)

        count = Reply.objects.get(user_id=user_id, id=id)

        count.useful_count -= 1

        count.unuseful_count += 1

        count.save()

        return Response({'messgae': '回答没用',
                         'success': True})

